<?php
include_once("../module/sns/config.php");

//贴纸
function get_paster_list(){
	global $db;
	$arr = array();
	$sql = "select * from ".SNSPASTER." where status>0 order by displayorder,create_time desc";
	$db->query($sql);
	$paster_list = $db->getRows();
	foreach ($paster_list as $val)
	{
		$arr[$val['id']] = $val['pic'];
	}
	
	return $arr;
}

if($_POST['act']=='save'){
    if($_POST['id'] && is_numeric($_POST['id'])){
        $set = "";
        $productid_error = 0;
        $pasterid_error = 0;
        $brandid_error = 0;
        $tagname_error = 0;
        if($_POST['tagname']!="" && ($_POST['tagname']!=$_POST['oldtagname'])){
        	$sql = "select id from ".SNSTAGS." where tagname='{$_POST['tagname']}' and id<>'{$_POST['id']}' limit 1";
        	$db->query($sql);
        	$existTagId = $db->fetchField('id');
        	if($existTagId>0){
        		$tagname_error = 1;
        	}else{
	            $set .= "tagname='".$_POST['tagname']."',";
        	}
//             //更新图片标签表话题名称
//             $sql = "update ".SNSPICTAGS." set tagname='".$_POST['tagname']."' where tagname='".$_POST['oldtagname']."'";
//             $db->query($sql);
//             //更新用户关注话题表话题名称
//             $sql = "update ".SNSFAVTAGS." set tagname='".$_POST['tagname']."' where tag_id='".$_POST['id']."'";
//             $db->query($sql);
//             //更新分享表的标签名称
//             $sql = "update ".SNS." set tags=replace(tags,'".$_POST['oldtagname']."','".$_POST['tagname']."') where find_in_set('".$_POST['oldtagname']."',tags)";
//         	$db->query($sql);
        }
        if($_POST['tag_type']=="2"){//品牌话题
	        if($_POST['brandid'] && $_POST['brand']){
	        	$sql = "select id from ".SNSTAGS." where brandid='{$_POST['brandid']}' and id<>'{$_POST['id']}' limit 1";
	        	$db->query($sql);
	        	$existId = $db->fetchField('id');
	        	if($existId>0){
	        		$brandid_error = 1;
	        	}else{
		            $set .= "brandid='".$_POST['brandid']."',";
		            $set .= "brand='".$_POST['brand']."',";
		            $set .= "productid='0',";
		            if($_POST['oldtagname']!=""){
		                $sql = "update ".SNSPICTAGS." set brandid='".$_POST['brandid']."',brand='".$_POST['brand']."' where tagname='".$_POST['oldtagname']."'";
		                $db->query($sql);   
		            }
	        	}
	        }else{
	        	$set .= "brandid='1',";
	        	$set .= "brand='',";
	        }
    	}elseif ($_POST['tag_type']=="3"){//商品话题
    		if($_POST['productid']>0){
    			$product_sql = "select id from ".PRO." where id='$_POST[productid]' limit 1";
    			$db->query($product_sql);
    			$product = $db->fetchRow();
    			if(!empty($product)){
    				$set .= "productid='$product[id]',";
    				$set .= "brandid='',";
    				$set .= "brand='',";
    			}else{
    				$productid_error = 1;
    			}
    		}else{
    			$productid_error = 1;
    		}
    	}else{
        	$set .= "productid='0',";
        	$set .= "brandid='',";
        	$set .= "brand='',";
        }
        
        if($_POST['paster_name'] && $_POST['paster_id']>0){
        	$sql = "select paster_id from ".SNSTAGS." where status=1 and paster_id>0 and id!='".$_POST['id']."' group by paster_id";
        	$db->query($sql);
        	$pasteridarr = $db->getRows();
        	$pasterids = array();
        	foreach ($pasteridarr as $pv)
        	{
        		$pasterids[] = $pv['paster_id'];
        	}
        	if(!in_array($_POST['paster_id'], $pasterids)){
	        	$set .= "paster_id='".$_POST['paster_id']."',";//贴纸ID
        	}else{
        		$pasterid_error = 1;
        	}
        }else{
        	$set .= "paster_id='0',";//贴纸ID
        }
        
        if(!$productid_error && !$pasterid_error && !$brandid_error && !$tagname_error){
        	if($_POST['tag_pics']){
        		$pics = explode(",", $_POST['tag_pics']);
        		if(count($pics)==3){
        			$set .= "pic='".$_POST['tag_pics']."',";
        		}
        	}else{
        		$set .= "pic='',";
        	}
        	
        	$set .= "description='".$_POST['description']."',";//描述
        	
        	$set .="logo='".$_POST['logo']."',";//LOGO
        	
        	if($_POST['status']!=""){
        		$set .= "status='".$_POST['status']."',";
        		if($_POST['status']<=0){
        			$sql = "delete from ".SNSFAVTAGS." where tag_id=".$_POST['id'];
        			$db->query($sql);
        		}
        	}
        	
        	if($set!=""){
        		$sql = "update ".SNSTAGS." set ".rtrim($set,",")." where id=".$_POST['id'];
        		$db->query($sql);
        		unset($_GET['s']);
        		unset($_GET['m']);
        		unset($_GET['act']);
        		unset($_GET['editid']);
        		msg('?m=sns&s=sns_tags.php'.'&'.http_build_query($_GET));
        	}
        }else{
        	msg('?m=sns&s=sns_tags.php&act=edit&productid_error='.$productid_error.'&pasterid_error='.$pasterid_error.'&brandid_error='.$brandid_error.'&tagname_error='.$tagname_error.'&tag_type='.$_POST['tag_type'].'&editid='.$_POST['id']);
        }
    }
}
if($_GET['act']=='op'){
    if(!empty($_GET['chk'])){
        $tagids = "";
        foreach ($_GET['chk'] as $tagid)
        {
            $tagids .= $tagid.",";
        }
        if($tagids!=""){
            if($_GET['set_status']!=""){
                $sql = "update ".SNSTAGS." set status='".$_GET['set_status']."' where id IN (".rtrim($tagids,",").")";
                $db->query($sql);
                if($_GET['status']<=0){
                	$sql = "delete from ".SNSFAVTAGS." where tag_id IN (".rtrim($tagids,",").")";
                	$db->query($sql);
                	msg('?m=sns&s=sns_tags.php');
                }
            }
        }
    }
}elseif($_GET['act']=='edit'){
    if($_GET['editid'] && is_numeric($_GET['editid'])){
        $sql = "select a.*,(select name from ".SNSPASTER." where id=a.paster_id) AS paster_name from ".SNSTAGS." a where id=".$_GET['editid']." limit 1";
        $db->query($sql);
        $de = $db->fetchRow();
        //贴纸
        $tpl->assign('paster_list',get_paster_list());
    }
}elseif($_GET['act']=='show_sns_list'){
	$sns_ids = "";
	if($_GET['tag_id']>0){
		$sql = "select sns_id from ".SNSPICTAGS." where tag_id='{$_GET['tag_id']}'";
		$db->query($sql);
		$snsIds = $db->getRows();
		if(!empty($snsIds)){
			foreach ($snsIds as $siv)
			{
				$sns_ids .= $siv['sns_id'].",";
			}
			$sns_ids = rtrim($sns_ids,",");
		}
	}
    $order = "";
    if($_GET['sdate']!='' && $_GET['edate']!='' && (strtotime($_GET['sdate'])<=strtotime($_GET['edate']))){
        $where .=" and a.create_time>='".$_GET['sdate']."' and a.create_time<='".$_GET['edate']."'";
    }else{
        if($_GET['sdate']!='' && $_GET['edate']==''){
            $where .=" and a.create_time>='".$_GET['sdate']."'";
        }
        if($_GET['sdate']=='' && $_GET['edate']!=''){
            $where .=" and a.create_time<='".$_GET['edate']."'";
        }
    }
    if($_GET['username']!=''){
        $where .=" and b.username like '$_GET[username]%'";
    }
//     if($_GET['tagname']!=''){
//         $where .=" and (a.tags like '$_GET[tagname]%' or a.tags like '%,$_GET[tagname]%')";
//     }
	if($sns_ids!=''){
		$where .= " and a.id in ({$sns_ids})";
	}
    if($_GET['brandid'] && $_GET['brand']){
        $where .=" and c.brandid='".$_GET['brandid']."'";
    }
    if($_GET['status']!=""){
        $where .=" and a.status='$_GET[status]'";
    }
    if($_GET['fnumsort']=="desc"){
        $order = "(select count(*) from ".SNSMF." where sns_id=a.id) desc,";
    }
    if($_GET['fnumsort']=="asc"){
        $order = "(select count(*) from ".SNSMF." where sns_id=a.id) asc,";
    }
    
    
    $sql = "select DISTINCT a.*,b.username as member_name,b.logo as member_photo from ".SNS." a left join ".MEMBER." b on a.member_id=b.userid left join ".SNSPICTAGS." c on a.id=c.sns_id where 1 ".$where." order by ".$order."create_time desc";
    
    include_once("../includes/page_utf_class.php");
    $page = new Page;
    $page->listRows=20;
    $db->query($sql);
    $totalRows = $db->num_rows();
    if (!$page->__get('totalRows')){
        $db->query($sql);
        $page->totalRows = $db->num_rows();
    }
    $sql .= "  limit ".$page->firstRow.",".$page->listRows;
    
    $db->query($sql);
    $de['page'] = $page->prompt();
    $de['list']=$db->getRows();
    
    foreach ($de['list'] as $k=>$v)
    {
        $sql = "select count(*) as totalNum from ".SNSMF." where sns_id=".$v['id'];
        $db->query($sql);
        $de['list'][$k]['favoriteNum'] = $db->fetchField('totalNum');
        $sql = "select brand from ".SNSPICTAGS." where sns_id=".$v['id']." limit 1";
        $db->query($sql);
        $brand = $db->fetchField('brand');
        $de['list'][$k]['brand'] = $brand?$brand:"暂无";
        $de['list'][$k]['tagname'] = $_GET['tagname'];
    }
}elseif($_GET['act']=='getFavoriteMember'){
    $de['favoriteMembers'] = array();
    if($_GET['tag_id']>0){
        $sql = "select member_id from ".SNSFAVTAGS." where tag_id=".$_GET['tag_id'];
        $db->query($sql);
        $members = $db->getRows();

        if(!empty($members)){
            $mIds = "";
            foreach ($members as $mv)
            {
                $mIds .= $mv['member_id'].",";
            }
            $sql = "select * from ".MEMBER." where userid in (".rtrim($mIds,",").")";
            $db->query($sql);
            include_once("../includes/page_utf_class.php");
            $page = new Page;
            $page->listRows=20;
            $db->query($sql);
            $totalRows = $db->num_rows();
            if (!$page->__get('totalRows')){
                $db->query($sql);
                $page->totalRows = $db->num_rows();
            }
            $sql .= "  limit ".$page->firstRow.",".$page->listRows;

            $db->query($sql);
            $de['page'] = $page->prompt();

            $de['favoriteMembers'] = $db->getRows();
        }
    }
}else{
    $where = "";
    $order = "";
    $timeorder = "desc";
    if($_GET['sdate']!='' && $_GET['edate']!='' && (strtotime($_GET['sdate'])<=strtotime($_GET['edate']))){
        $where .=" and a.create_time>='".$_GET['sdate']."' and a.create_time<='".$_GET['edate']."'";
    }else{
        if($_GET['sdate']!='' && $_GET['edate']==''){
            $where .=" and a.create_time>='".$_GET['sdate']."'";
        }
        if($_GET['sdate']=='' && $_GET['edate']!=''){
            $where .=" and a.create_time<='".$_GET['edate']."'";
        }
    }
    if($_GET['username']!=''){
        $where .=" and a.create_user like '%$_GET[username]%'";
    }
    if($_GET['tagname']!=''){
        $where .=" and a.tagname like '%".mysql_escape_string($_GET[tagname])."%'";
    }
    if($_GET['brandid'] && $_GET['brand']){
        $where .=" and a.brandid='".$_GET['brandid']."'";
    }elseif ($_GET['brand']!=''){
    	$where .=" and a.brand LIKE '%".mysql_escape_string($_GET['brand'])."%'";
    }
    if($_GET['pasterName']!=""){
    	$where .=" and b.name like '%$_GET[pasterName]%'";
    }
    if($_GET['status']!=""){
        $where .=" and a.status='$_GET[status]'";
    }
    if($_GET['is_desc']!=""){
        if($_GET['is_desc']){
            $where .=" and a.description!=''";
        }else{
            $where .=" and (a.description='' or a.description is null)";
        }
    }
    if($_GET['is_pics']!=""){
        if($_GET['is_pics']){
            $where .=" and a.pic!=''";
        }else{
            $where .=" and (a.pic='' or a.pic is null)";
        }
    }
    if($_GET['tagType']!=""){
    	switch ($_GET['tagType']){
    		case 0:
    			$where .=" and (a.brandid is null) and a.productid=0";break;
    		case 1:
    			$where .=" and a.productid>0";break;
    		case 2:
    			$where .=" and a.brandid>1";break;
    		case 3:
    			$where .=" and a.brandid=1";break;
    		default:
    			break;
    	}
    }
    if($_GET['order']=="desc"){
        $order = "(select count(*) from ".SNSFAVTAGS." where tag_id=a.id) desc,";
    }
    if($_GET['order']=="asc"){
        $order = "(select count(*) from ".SNSFAVTAGS." where tag_id=a.id) asc,";
    }
    if($_GET['timeorder']=='asc'){
        $timeorder = "asc";
    }
    
    $sql = "select a.* from ".SNSTAGS." a left join ".SNSPASTER." b on a.paster_id=b.id where 1".$where." order by ".$order."create_time ".$timeorder;
    include_once("../includes/page_utf_class.php");
    $page = new Page;
    $page->listRows=20;
    $db->query($sql);
    $totalRows = $db->num_rows();
    if (!$page->__get('totalRows')){
        $db->query($sql);
        $page->totalRows = $db->num_rows();
    }
    $sql .= "  limit ".$page->firstRow.",".$page->listRows;
    
    $db->query($sql);
    $de['page'] = $page->prompt();
    $de['list']=$db->getRows();
    
    //贴纸
    $paster_arr = get_paster_list();
    //关注数统计
    foreach ($de['list'] as $lk=>$lv)
    {
        $sql = "select count(*) as totalNum from ".SNSFAVTAGS." where tag_id=".$lv['id'];
        $db->query($sql);
        $de['list'][$lk]['tag_favorite_count'] = $db->fetchField('totalNum');
        $de['list'][$lk]['paster_pic'] = $paster_arr[$lv['paster_id']];
    }
    unset($_GET['s']);
    unset($_GET['m']);
    if (count($_GET)){
    	$tpl->assign("edit_url",http_build_query($_GET));//编辑时带上列表的条件
    }
}

$tpl->assign('countpro',$totalRows);
$tpl->assign('de',$de);
$tpl->assign('img_url_pre',$img_url_pre);
$tpl->display('sns_tags.htm');
?>